import { arrMethods } from './array';
import {
    def
} from '../utils'

export class Observer {
    constructor(value) {
        def(value, '__ob__', this);
        if(Array.isArray(value)) {
            // [] 处理
            value.__proto__ = arrMethods;
            this.observeArr(value);
        } else {
            // {} 处理
            this.walk(value);
        }
    }
    walk(obj) {
        const keys = Object.keys(obj);
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            const value = obj[key];
            defineReactive(obj, key, value);
        }
    }
    observeArr(arr) {
        for(let i = 0; i < arr.length; i++) {
            observe(arr[i]);
        } 
    }
}

export function observe(value) {
    if (typeof value !== 'object' || value === null) return;
    let ob;
    if (value.__ob__ instanceof Observer) {
        ob = value.__ob__;
    } else {
        ob = new Observer(value);
    }
    return ob;
}
export function defineReactive(obj, key, value) {
    observe(value);
    Object.defineProperty(obj, key, {
        get() {
            console.log('监测到获取', value);
            return value;
        },
        set(newValue) {
            if(newValue === value) return;
            observe(newValue);
            obj[key] = newValue;
        }
    })
}